package org.example.springboot;


import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;

@RestController
@RequestMapping("/test2")
public class Test2 {
    @RequestMapping("/getCookie")
    public String getCookie(HttpServletRequest request) {

        Cookie[] cookies = request.getCookies();

        if (cookies == null) {
            return "cookie为空";
        }

        Arrays.stream(cookies).forEach(x -> {
            // cookie也是键值对的形式
            System.out.println(x.getName() + ":" + x.getValue());
        });

        // 等价于
        for(Cookie x : cookies) {
            System.out.println(x.getName() + ":" + x.getValue());
        }
        return "获取Cookie成功";
    }

    @RequestMapping("/getCookie2")
    public String getCookie2(@CookieValue("Cookie_3") String test) {
        return "cookie = " + test;
    }


    @RequestMapping("/setSession")
    public String setSession(HttpServletRequest request) {
        HttpSession session = request.getSession();
        session.setAttribute("userInfo","张三的用户信息");
        return "设置Session成功";
    }


    @RequestMapping("/getSession")
    public String getSession(HttpServletRequest request) {
        HttpSession session = request.getSession();
        String userInfo = (String)session.getAttribute("userInfo");
        return "获取用户信息:" + userInfo;
    }

    @RequestMapping("/getSession2")
    public String getSession2(HttpSession session) {
        //HttpSession session = request.getSession();
        String userInfo = (String)session.getAttribute("userInfo");
        return "获取用户信息:" + userInfo;
    }


    @RequestMapping("/getSession3")
    public String getSession3(@SessionAttribute("userInfo") String userInfo) {
        return "获取用户信息:" + userInfo;
    }

    @RequestMapping("/getHeader")
    public String getHeader(HttpServletRequest request) {
        String userAgent = request.getHeader("User-Agent");
        return userAgent;
    }

    @RequestMapping("/getHeader2")
    public String getHeader2(@RequestHeader("User-Agent") String userAgent) {
        return "userAgent：" + userAgent;
    }
}
